package com.wzs.repository.impl;

import com.wzs.bean.User;
import com.wzs.repository.BaseRepository;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Repository
public class UserRepository implements BaseRepository<User,Integer> {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }

    public User get(Integer id) {
        return (User)getCurrentSession().load(User.class,id);
    }

    public List<User> findAll() {
        return null;
    }


    public Integer save(User entity) {
        return (Integer)getCurrentSession().save(entity);
    }

    public void update(User entity) {
        getCurrentSession().update(entity);
    }

    public void delete(Integer id) {
        getCurrentSession().delete(get(id));
    }

    public void flush() {
        getCurrentSession().flush();
    }

    //条件查询
    public List<User> getByMap(Map<String,String> map){
        Criteria criteria = getCurrentSession().createCriteria(User.class);
        Set<Map.Entry<String, String>> entries = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            Criterion criterion = Restrictions.eq(next.getKey(), next.getValue());
            criteria.add(criterion);
        }
        List<User> list = criteria.list();
        return list;
    }
}
